package com.wb.utils

import com.wb.component.Slf4j
import com.wb.component.Slf4j.Companion.log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.InputStream
import java.time.LocalDate
import java.time.format.DateTimeFormatter

/**
 * 摸鱼工具
 *
 * @author 祁雪
 */
@Slf4j
class TouchFishUtil {

    companion object {

        //        const val API = "https://api.j4u.ink/proxy/remote/moyu.json"
        const val API = "https://api.j4u.ink/v1/store/other/proxy/remote/moyu.json"

        fun getImg(path: String): InputStream? {

            try {

                val fileName = "${LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))}.png"

                var file = File(path, fileName)
                if (file.exists()) {
                    return file.inputStream()
                }

                val respose = RestUtil.send(API, null, null, 0, String::class.java)

                println(respose.body)

                val gson = Gson()

                var map = gson.fromJson(
                    respose.body,
                    object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                if (map.containsKey("data")) {

                    map = gson.fromJson(
                        gson.toJson(map.get("data")),
                        object : TypeToken<HashMap<String, Any>>() {}.type
                    ) as HashMap<String, Any>

                    if (map.containsKey("moyu_url")) {
                        FileNetUtil.downHttpUrl(map.get("moyu_url").toString(), path, fileName)

                        file = File(path, fileName)
                        return file.inputStream()
                    }

                }

            } catch (e: Exception) {
                log.error("摸鱼日历获取失败", e)
            }

            return null

        }

        fun getImgFile(path: String): File? {

            val fileName = "${LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))}.png"

            val file = File(path, fileName)
            if (file.exists()) {
                return file
            }

            val inputStream = getImg(path)

            if (inputStream == null) {
                return null
            }

            file.writeBytes(inputStream.readAllBytes())

            return file
        }

    }

}

fun main() {
}